package think.thread.deadlock.c01;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class PhilosophersExecutor {

	public static void main(String[] args) throws Exception {
		int personSize = 5;
		int time = -1;
		Chopstick[] chopsticks = initChopsticks(personSize);

		Philosopher[] philosophers = new Philosopher[personSize];
		for (int i = 0; i < personSize; i++) {
			philosophers[i] = new Philosopher(chopsticks[i], chopsticks[(i + 1)
					% personSize], i, time);
		}
		ExecutorService service = Executors.newCachedThreadPool();

		for (int i = 0; i < personSize; i++) {
			service.execute(philosophers[i]);
		}
		boolean exitFlag = true;
		if (exitFlag) {
			TimeUnit.SECONDS.sleep(5);
		} else {
			System.out.println("Press 'Enter' to quit ");
			System.in.read();
		}
		service.shutdownNow();
	}

	public static Chopstick[] initChopsticks(int size) {
		Chopstick[] chopsticks = new Chopstick[size];
		for (int i = 0; i < size; i++) {
			chopsticks[i] = new Chopstick();
		}
		return chopsticks;
	}

}
